package kd.hc.ecco;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.id.ID;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.util.StringUtils;
import kd.hc.utils.BusinessDataServiceHelperExt;
import kd.hc.utils.JsonUtil;
import kd.hc.utils.OperationServiceUtil;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 目标成本变更 服务插件
 */
public class TargetCostUpdateBillServicePlugIn extends AbstractOperationServicePlugIn implements Plugin {
    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        String operationKey = e.getOperationKey();
        switch (operationKey) {
            case "audit"://审核生成合约规划
                editTargetCost(e.getDataEntities());
                break;
        }
    }

    private void editTargetCost(DynamicObject[] dataEntities) {
        if (dataEntities != null && dataEntities.length >= 1) {
            for (int i = 0; i < dataEntities.length; i++) {
                DynamicObject dataEntity = dataEntities[i];
                String id = dataEntity.getString("id");
                //来源目标成本变更
                DynamicObject targetCostUpdate = BusinessDataServiceHelper.loadSingle(id, "hc95_target_costupdate");
                DynamicObjectCollection targetCostUpdateLDEn = targetCostUpdate.getDynamicObjectCollection("hc95_building_all");
                //目标
                DynamicObject targetCost = BusinessDataServiceHelper.loadSingle(targetCostUpdate.getString("hc95_mbcbd_id"), "hc95_target_cost");
                DynamicObjectCollection targetCostLDEn = targetCost.getDynamicObjectCollection("hc95_building_all");
                String versionNew = targetCostUpdate.getString("hc95_version_new");//最新版本
                BigDecimal newVersionNumber = targetCostUpdate.getBigDecimal("hc95_newversion_number");//最新版本号

                //修改
                targetCost.set("hc95_version", versionNew);
                targetCost.set("hc95_version_number", newVersionNumber);
                //明细
                DynamicObjectCollection entryentityOld = targetCost.getDynamicObjectCollection("hc95_tree_entryentity");//原明细信息
                DynamicObjectCollection entryentityUpdate = targetCostUpdate.getDynamicObjectCollection("hc95_tree_entryentity");//新明细信息
                //最大的seq
                int seqMax = 1;
                List<Integer> seqList = entryentityOld.stream().map(m1 -> m1.getInt("seq")).collect(Collectors.toList());
                if (seqList != null && seqList.size() >= 1) {
                    seqMax = Collections.max(seqList);
                }
                if (entryentityUpdate != null && entryentityUpdate.size() >= 1) {
                    //1.分录变更
                    List<DynamicObject> updateEnColl = entryentityUpdate.stream().collect(Collectors.toList());
                    // 1.1 将所有新增行情况的长id换成 目标成本单id
                    Map<String, String> costTypeId = new HashMap<>();
                    List<DynamicObject> idsQK_1 = updateEnColl.stream().filter(f1 -> ((f1.getString("hc95_oldmbcbmx_id") == null ? "" : f1.getString("hc95_oldmbcbmx_id")).length() >= 2)).collect(Collectors.toList());
                    for (DynamicObject idsQKRow : idsQK_1) {
                        String idNew = idsQKRow.getString("id");
                        String hc95_oldmbcbmx_id = idsQKRow.getString("hc95_oldmbcbmx_id");
                        costTypeId.put(idNew, hc95_oldmbcbmx_id);
                    }
                    List<DynamicObject> idsQK_2 = updateEnColl.stream().filter(f1 -> ((f1.getString("hc95_oldmbcbmx_id") == null ? "" : f1.getString("hc95_oldmbcbmx_id")).length() <= 1)).collect(Collectors.toList());
                    for (DynamicObject idsQKRow : idsQK_2) {
                        String idNew = idsQKRow.getString("id");
                        long newId = ID.genLongId();
                        costTypeId.put(idNew, String.valueOf(newId));
                    }
                    // 2.处理新增修改的情况
                    for (DynamicObject updateEnRow : updateEnColl) {
                        String oldmbcbmxId = updateEnRow.getString("hc95_oldmbcbmx_id");//来源目标成本行ID
                        BigDecimal priceX = updateEnRow.getBigDecimal("hc95_price_en_x");//新单价
                        BigDecimal qtyX = updateEnRow.getBigDecimal("hc95_qty_sum_en_x");//新数量
                        BigDecimal zxmucbe = updateEnRow.getBigDecimal("hc95_zxmucbe_sum_en");//原目标成本额
                        BigDecimal ysmucbe = updateEnRow.getBigDecimal("hc95_ysmucbe_sum_en");//现目标成本额
                        BigDecimal sex = updateEnRow.getBigDecimal("hc95_se_sum_en_x");//现税额
                        DynamicObject accoun = updateEnRow.getDynamicObject("hc95_accoun_en");//会计科目
                        DynamicObject unit = updateEnRow.getDynamicObject("hc95_unit_en");//单位
                        DynamicObject slx = updateEnRow.getDynamicObject("hc95_sl_sum_en_x");//税率
                        if (StringUtils.isNotEmpty(oldmbcbmxId)) {
                            //修改 目前只会改 数量 单价 税率 会计科目
                            Optional<DynamicObject> oldRowEnOp = entryentityOld.stream().filter(f1 -> f1.getString("id").equals(oldmbcbmxId)).findFirst();
                            if (oldRowEnOp.isPresent()) {
                                DynamicObject oldRow = oldRowEnOp.get();
                                oldRow.set("hc95_price_en", priceX);//单价
                                oldRow.set("hc95_qty_sum_en", qtyX);//数量
                                oldRow.set("hc95_ysmucbe_sum_en", ysmucbe);//原目标成本额
                                oldRow.set("hc95_zxmucbe_sum_en", zxmucbe);//现目标成本额
                                oldRow.set("hc95_se_sum_en", sex);//现税额
                                oldRow.set("hc95_sl_sum_en", slx);//税率
                                oldRow.set("hc95_accoun_en", accoun);//会计科目
                                oldRow.set("hc95_unit_en", unit);//单位
                            } else {
                                throw new KDBizException("目标成本变更单数据异常目标成本明细Id[" + oldmbcbmxId + "]被错误删除!");
                            }
                        } else {
                            //新增
                            String idUpdate = updateEnRow.getString("id");
                            String longIdUpdate = updateEnRow.getString("hc95_longid_en");
                            DynamicObject hc95_cost_item_en = updateEnRow.getDynamicObject("hc95_cost_item_en");//成本类型
                            int hc95_rank_en = updateEnRow.getInt("hc95_rank_en");//层级
                            boolean hc95_is_leaf = updateEnRow.getBoolean("hc95_is_leaf");//是否叶子节点

                            DynamicObject newRowEn = entryentityOld.addNew();
                            newRowEn.set("hc95_cost_item_en", hc95_cost_item_en);//单价
                            newRowEn.set("hc95_price_en", priceX);//单价
                            newRowEn.set("hc95_qty_sum_en", qtyX);//数量
                            newRowEn.set("hc95_ysmucbe_sum_en", ysmucbe);//原目标成本额
                            newRowEn.set("hc95_zxmucbe_sum_en", zxmucbe);//现目标成本额
                            newRowEn.set("hc95_se_sum_en", sex);//现税额
                            newRowEn.set("hc95_sl_sum_en", slx);//税率
                            newRowEn.set("hc95_accoun_en", accoun);//会计科目
                            newRowEn.set("hc95_unit_en", unit);//单位
                            newRowEn.set("hc95_rank_en", hc95_rank_en);//层级
                            newRowEn.set("hc95_is_leaf", hc95_is_leaf);//是否叶子节点
                            //处理id和长id
                            newRowEn.set("id", costTypeId.get(idUpdate));
                            if (StringUtils.isNotEmpty(longIdUpdate)) {
                                seqMax = seqMax + 1;
                                String longIdNew = "";
                                String[] longIdUpdateArr = longIdUpdate.split("\\.");
                                int longIdUpdateArrLe = longIdUpdateArr.length;
                                int longIdUpdateArrLePa = longIdUpdateArrLe - 2;
                                String pid = "0";
                                for (int n = 0; n < longIdUpdateArrLe; n++) {
                                    String idNew = costTypeId.get(longIdUpdateArr[n]);
                                    longIdNew = longIdNew + idNew + ".";
                                }
                                if (longIdUpdateArrLePa >= 0) {
                                    pid = costTypeId.get(longIdUpdateArr[longIdUpdateArrLePa]);
                                }
                                newRowEn.set("seq", seqMax);
                                newRowEn.set("pid", pid);
                                longIdNew = longIdNew.substring(0, longIdNew.length() - 1);
                                newRowEn.set("hc95_longid_en", longIdNew);//长id
                            } else {
                                throw new KDBizException("目标成本变更单数据异常存在长Id为空!");
                            }
                        }
                    }

                }

                //楼栋
                for (int j = 0; j < targetCostLDEn.size(); j++) {
                    DynamicObject rowEnLD = targetCostLDEn.get(j);
                    String rowEnLDId = rowEnLD.getPkValue().toString();
                    rowEnLD.set("hc95_ysmucbe_ld1", rowEnLD.get("hc95_zxmucbe_ld1"));
                    DynamicObjectCollection buildingZb = rowEnLD.getDynamicObjectCollection("hc95_building_zb");
                    Optional<DynamicObject> hc95_oldmbcbmx_ldid = targetCostUpdateLDEn.stream().filter(f1 -> f1.getString("hc95_oldmbcbmx_ldid").equals(rowEnLDId)).findFirst();
                    if (hc95_oldmbcbmx_ldid.isPresent()) {
                        DynamicObject rowEnLDUpdate = hc95_oldmbcbmx_ldid.get();
                        DynamicObjectCollection buildingZbUpdate = rowEnLDUpdate.getDynamicObjectCollection("hc95_building_zb");
                        rowEnLD.set("hc95_unit_ld1", rowEnLDUpdate.get("hc95_unit_ld1"));
                        rowEnLD.set("hc95_qty_ld1", rowEnLDUpdate.get("hc95_qty_ld1"));
                        rowEnLD.set("hc95_zxmucbe_ld1", rowEnLDUpdate.get("hc95_zxmucbe_ld1"));
                        rowEnLD.set("hc95_sl_ld1", rowEnLDUpdate.get("hc95_sl_ld1"));
                        rowEnLD.set("hc95_se_ld1", rowEnLDUpdate.get("hc95_se_ld1"));
                        buildingZb.forEach(lditem -> {
                            String ldZbId = lditem.getPkValue().toString();
                            lditem.set("hc95_ysmucbe_ldzb", lditem.get("hc95_zxmucbe_ldzb"));
                            Optional<DynamicObject> hc95_oldmbcbmx_zbid = buildingZbUpdate.stream().filter(f1 -> f1.getString("hc95_oldmbcbmx_zbid").equals(ldZbId)).findFirst();
                            if (hc95_oldmbcbmx_zbid.isPresent()) {
                                DynamicObject rowEnLDZBUpdate = hc95_oldmbcbmx_zbid.get();
                                lditem.set("hc95_unit_ldzb", rowEnLDZBUpdate.get("hc95_unit_ldzb"));
                                lditem.set("hc95_qty_ldzb", rowEnLDZBUpdate.get("hc95_qty_ldzb"));
                                lditem.set("hc95_zxmucbe_ldzb", rowEnLDZBUpdate.get("hc95_zxmucbe_ldzb"));
                                lditem.set("hc95_sl_ldzb", rowEnLDZBUpdate.get("hc95_sl_ldzb"));
                                lditem.set("hc95_se_ldzb", rowEnLDZBUpdate.get("hc95_se_ldzb"));
                            }
                        });
                    }
                }

                //保存目标成本
                OperationServiceUtil.save("hc95_target_cost", targetCost);
                //合约规划
                targetCost = BusinessDataServiceHelper.loadSingle(targetCostUpdate.getString("hc95_mbcbd_id"), "hc95_target_cost");
                OperateOption option = OperateOption.create();
                OperationResult operationResult = OperationServiceHelper.executeOperate("dogenContractPlanning", "hc95_target_cost", new DynamicObject[]{targetCost}, option);
                String operationResultErrorInfos = OperationServiceUtil.getOperationResultErrorInfos(operationResult);
                if (StringUtils.isNotEmpty(operationResultErrorInfos)) {
                    throw new KDBizException(operationResultErrorInfos);
                }

            }
        }

    }


}